package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.commons.util.PageInfoToPageDataConverter;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.CategoryAttributeTemplateMapper;
import cn.tedu.csmall.product.mapper.CategoryMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.entity.BrandCategory;
import cn.tedu.csmall.product.pojo.entity.Category;
import cn.tedu.csmall.product.pojo.entity.CategoryAttributeTemplate;
import cn.tedu.csmall.product.pojo.entity.Spu;
import cn.tedu.csmall.product.pojo.param.CategoryAddNewParam;
import cn.tedu.csmall.product.pojo.param.CategoryUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.*;
import cn.tedu.csmall.product.service.ICategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {
    
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private BrandCategoryMapper brandCategoryMapper;

    @Autowired
    private CategoryAttributeTemplateMapper categoryAttributeTemplateMapper;


    @Override
    public void updateById(Long id, CategoryUpdateInfoParam categoryUpdateInfoParam) {
        log.debug("开始处理[修改类别详情]的业务，参数:{}",categoryUpdateInfoParam);
        Category category= categoryMapper.selectById(id);
        log.debug("根据ID={}检查类别数据是否存在,查询结果:{}",id,category);
        if (category == null){
            String message = "修改类别失败，修改的类别不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        BeanUtils.copyProperties(categoryUpdateInfoParam,category);
        category.setId(id);
        categoryMapper.updateById(category);
        log.debug("将新的类别数据更新到数据库，完成！");
    }

    @Override
    public void delete(Long categoryId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",categoryId);
        int countById = categoryMapper.selectCount(queryWrapper);
        log.debug("根据类别ID统计匹配的类别数量，结果:{}",countById);
        if(countById == 0 ){
            String message = "删除类别失败，类别数据不存在!";
            log.warn(message);
            throw  new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //检查是否有Spu关联到了此品牌，如果存在，则抛出异常
        QueryWrapper<Spu> queryWrapper1 = new QueryWrapper<Spu>();
        queryWrapper1.eq("category_id",categoryId);
        int countByAlbumId1 = spuMapper.selectCount(queryWrapper1);
        log.debug("根据品牌ID统计匹配的图片数量，结果:{}",countByAlbumId1);
        if (countByAlbumId1 > 0 ){
            String message = "删除品牌失败，仍有图片关联到此品牌";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        //检查是否有brand关联到了此品牌，如果存在，则抛出异常
        QueryWrapper<BrandCategory> queryWrapper2 = new QueryWrapper<BrandCategory>();
        queryWrapper2.eq("category_id",categoryId);
        int countByAlbumId2 = brandCategoryMapper.selectCount(queryWrapper2);
        log.debug("根据品牌ID统计匹配的图片数量，结果:{}",countByAlbumId2);
        if (countByAlbumId2 > 0 ){
            String message = "删除品牌失败，仍有图片关联到此品牌";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }


        //检查是否有category-attribute关联到了此品牌，如果存在，则抛出异常
        QueryWrapper<CategoryAttributeTemplate> queryWrapper3 = new QueryWrapper<CategoryAttributeTemplate>();
        queryWrapper3.eq("category_id",categoryId);
        int countByAlbumId3 = categoryAttributeTemplateMapper.selectCount(queryWrapper3);
        log.debug("根据品牌ID统计匹配的图片数量，结果:{}",countByAlbumId3);
        if (countByAlbumId3 > 0 ){
            String message = "删除品牌失败，仍有图片关联到此品牌";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }


        categoryMapper.deleteById(categoryId);
    }

    @Override
    public void addNew(CategoryAddNewParam categoryAddNewParam) {

        // 调用参数对象的getName()得到尝试添加的类别的名称
        String name = categoryAddNewParam.getName();
        // 调用Mapper对象的countByName()执行统计查询
        int count = categoryMapper.countByName(name);
        log.debug("根据名称【{}】统计数量，结果：{}", name, count);
        // 判断统计结果是否大于0
        if(count > 0 ){
            //名称被占用，抛出异常
            String message = "添加类别失败，类别名称已经被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        //通过参数对象获取parentId
        Long parentId = categoryAddNewParam.getParentId();
        //预设depth(深度值)为1
        Integer depth = 1;
        CategoryStandardVO parentCategory = null;
        //判断parentId是否不为0
        if(parentId != 0){
            //否，调用Mapper对象的getStandardById()查询父级类别
            parentCategory = categoryMapper.getStandardById(parentId);
            //判断查询结果(父级类别)是否为null
            if (parentCategory == null){
                //是，抛出异常
                String message = "添加类别失败，父级类别不存在";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
            }
            else {
                //否，depth(深度值)为,父级类别的depth+1
                depth = parentCategory.getDepth()+1;
            }
        }


        //将类别数据写入到数据库中,创建Category对象
        Category category = new Category();
        //复制属性
        BeanUtils.copyProperties(categoryAddNewParam, category);

        //补全Category对象的属性值，depth
        category.setDepth(depth);

        //补全Category对象的属性值 :isParent >>>固定为0
        category.setIsParent(0);
        // 调用Mapper对象的insert()方法执行插入

        log.debug("准备将新的类别数据写入到数据库，数据：{}",category);
        int rows = categoryMapper.insert(category);
        if (rows != 1) {
            String message = "添加类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的类别数据写入到数据库，完成！");


        // 判断parentId是否不为0，并判断父级类别的isParent是否为0
        if (parentId != 0 && parentCategory.getIsParent() == 0) {
            // 是：将父级类别的isParent更新为1
            Category updateParentCategory = new Category();
            updateParentCategory.setId(parentId);
            updateParentCategory.setIsParent(1);
            rows = categoryMapper.update(updateParentCategory);
            if (rows != 1) {
                String message = "添加类别失败，服务器忙，请稍后再尝试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }

    }

    @Override
    public PageData<CategoryListItemVO> list(Integer pageNum, Integer pageSize) {

        log.debug("开始处理[查询类别列表]的业务，页码：{},每页记录数:{}",pageNum,pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<CategoryListItemVO> list = categoryMapper.list();
        PageInfo<CategoryListItemVO> pageInfo = new PageInfo<>(list);
        PageData<CategoryListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成,即将返回：{}",pageData);
        return pageData;
    }

    @Override
    public PageData<CategoryListItemVO> list(Integer page) {
        Integer pageSize = 5;
        return list(page,pageSize);
    }

    @Override
    public CategoryStandardVO getStandardById(Long id) {

        log.debug("开始处理[根据ID类别详情]的业务，参数:{}",id);
        CategoryStandardVO queryResult = categoryMapper.getStandardById(id);
        if(queryResult == null){
            String message = "查询类别详情失败，类别数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return queryResult;
    }

    @Override
    public List<CategoryTreeItemVO> listTree() {
        log.debug("开始处理[获取类别树]的业务，参数:无");
        List<CategoryTreeItemVO> categoryTree = new ArrayList<>();

        List<CategoryListItemVO> categoryList = categoryMapper.list();
        Map<Long , CategoryListItemVO> allCategoryMap = transformListToMap(categoryList);
        for (Long key : allCategoryMap.keySet()) {
            CategoryListItemVO mapItem = allCategoryMap.get(key);
            if (mapItem.getParentId() == 0){
                CategoryTreeItemVO categoryTreeItemVO = convertListItemToTreeItem(mapItem);
                categoryTree.add(categoryTreeItemVO);

                fillChildren(mapItem,categoryTreeItemVO,allCategoryMap);

            }
        }

        return categoryTree;
    }

    @Override
    public void setEnable(Long id) {
        log.debug("开始处理【启用类别】的业务，参数：{}", id);
        updateEnableById(id, 1);
    }

    private void updateEnableById(Long id, Integer enable) {
        // 调用Mapper对象的getStandardById()方法执行查询
        CategoryStandardVO currentCategory = categoryMapper.getStandardById(id);
        // 判断查询结果是否为null，如果是，则抛出异常
        if (currentCategory == null) {
            String message ="类别失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断查询结果中的enable与参数enable是否相同，如果是，则抛出异常（当前状态与目标状态相同，没必要执行更新）
        if (currentCategory.getEnable() == enable) {
            String message = "类别失败，此类别已经处于" + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 创建Category对象
        Category updateCategory = new Category();
        // 向Category对象中封装属性值：id, enable，均来自方法参数
        updateCategory.setId(id);
        updateCategory.setEnable(enable);
        // 调用Mapper对象的update()方法执行更新
        int rows = categoryMapper.update(updateCategory);
        if (rows != 1) {
            String message ="类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public void setDisable(Long id) {
        log.debug("开始处理【禁用类别】的业务，参数：{}", id);
        updateEnableById(id, 0);
    }













    //类别树的方法
    private Map<Long, CategoryListItemVO> transformListToMap(List<CategoryListItemVO> categoryList) {
        Map<Long, CategoryListItemVO> categoryMap = new LinkedHashMap<>();
        for (CategoryListItemVO categoryListItemVO : categoryList) {
            if (categoryListItemVO.getEnable() == 0) {
                continue;
            }
            categoryMap.put(categoryListItemVO.getId(), categoryListItemVO);
        }
        return categoryMap;
    }




    private CategoryTreeItemVO convertListItemToTreeItem(CategoryListItemVO listItem) {
        return new CategoryTreeItemVO()
                .setValue(listItem.getId())
                .setLabel(listItem.getName());
    }




    private void fillChildren(CategoryListItemVO listItem, CategoryTreeItemVO currentTreeItem, Map<Long, CategoryListItemVO> allCategoryMap) {
        if (listItem.getIsParent() == 1) {
            currentTreeItem.setChildren(new ArrayList<>());
            Set<Long> keySet = allCategoryMap.keySet();
            for (Long key : keySet) {
                CategoryListItemVO mapItem = allCategoryMap.get(key);
                if (mapItem.getParentId() == listItem.getId()) {
                    CategoryTreeItemVO categoryTreeSubItemVO = convertListItemToTreeItem(mapItem);
                    currentTreeItem.getChildren().add(categoryTreeSubItemVO);
                    if (mapItem.getIsParent() == 1) {
                        fillChildren(mapItem, categoryTreeSubItemVO, allCategoryMap);
                    }
                }
            }
        }
        System.out.println();
    }







}
